<template>
    <div class="signature-box">
        <div class="signature-canvas" ref="canvasBox">
            <canvas ref="signatureCanvas" @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp"
                @mouseout="handleMouseOut"></canvas>
        </div>
        <!-- 	<div class="signature-btns">
			 <el-button plain @click="reWrite">重写</el-button>
			 <el-button class="btnbg"  @click="submitSignature">提交签名</el-button>
		</div> -->
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineExpose } from 'vue';
let canvasBox: any = ref(null)
let signatureCanvas: any = ref(null)
let canvasTxt: any = null

let startX = 0
let startY = 0

let isDown = false

let imgSrc = ref('')

const handleMouseDown = (e: any) => {
    let obj = { x: e.offsetX, y: e.offsetY }
    startX = obj.x
    startY = obj.y
    canvasTxt.beginPath()
    canvasTxt.moveTo(startX, startY)
    canvasTxt.lineTo(obj.x, obj.y)
    canvasTxt.stroke()
    canvasTxt.closePath()
    isDown = true
}

const handleMouseMove = (e: any) => {
    if (isDown) {
        let obj = { x: e.offsetX, y: e.offsetY }
        canvasTxt.beginPath()
        canvasTxt.moveTo(startX, startY)
        canvasTxt.lineTo(obj.x, obj.y)
        canvasTxt.stroke()
        canvasTxt.closePath()
        startX = obj.x
        startY = obj.y
    }
}

const handleMouseUp = (e: any) => {
    isDown = false
}

const handleMouseOut = () => {
    isDown = false
}

const reWrite = () => {
    canvasTxt.clearRect(0, 0, 560, 300)
}

const submitSignature = () => {
    imgSrc.value = signatureCanvas.value.toDataURL()
}
onMounted(() => {
    signatureCanvas.value.width = 560
    signatureCanvas.value.height = 300
    canvasTxt = signatureCanvas.value.getContext("2d")
})
defineExpose({
    reWrite,
    submitSignature,
    imgSrc
})
</script>

<style lang="scss" scoped>
.signature-box {
    height: 100%;

    .signature-canvas {
        border: 1px solid #e5e5e5;
    }

    .signature-btns {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-top: 15px;

        .btn {
            height: 30px;
            line-height: 30px;
            border: 1px solid black;
            padding: 0 6px;
            border-radius: 4px;
            cursor: pointer;
        }

        .gray {
            background-color: gray;
        }

        .green {
            background-color: green;
        }
    }

    .img-area {
        height: 200px;
        border: 1px solid gray;

        img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }
}

.ml20 {
    margin-left: 20px;
}
</style>